package top.mollysu.sell.controller.seller;

import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import top.mollysu.sell.VO.ResultVO;
import top.mollysu.sell.exception.SellException;
import top.mollysu.sell.form.SellerForm;
import top.mollysu.sell.pojo.SellerInfo;
import top.mollysu.sell.service.SellerService;
import top.mollysu.sell.util.PasswordUtils;
import top.mollysu.sell.util.ResultVOUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author kosmosr
 * @Date 2018/3/16
 */
@Controller
@Log4j2
@RequestMapping("/seller")
public class SellerUserController {

    @Autowired
    private SellerService sellerService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/login")
    public ModelAndView index() {
        return new ModelAndView("user/login.btl");
    }

    @PostMapping("/login")
    @ResponseBody
    public ResultVO login(@PathVariable@RequestBody @Valid SellerForm form,
                          BindingResult bindingResult,
                          Map<String, Object> map,
                          HttpServletResponse response) {
        if (bindingResult.hasErrors()) {
            map.put("msg", bindingResult.getFieldError().getDefaultMessage());
            return ResultVOUtils.success(map);
        }

        SellerInfo sellerInfo = sellerService.findSellerByUsername(form.getUsername());
        if (sellerInfo == null) {
            return ResultVOUtils.error("登录失败");
        }

        if (!PasswordUtils.equalPwd(form.getPassword(), sellerInfo.getPassword())) {
            map.put("msg", "用户名或者密码错误");
            return ResultVOUtils.success(map);
        }

        String uuid = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set("token_"+uuid, sellerInfo.getUsername(), 7200, TimeUnit.SECONDS);
        Cookie cookie = new Cookie("token", uuid);
        cookie.setMaxAge(7200);
        cookie.setPath("/");
        response.addCookie(cookie);
        return ResultVOUtils.success();
    }

}
